package com.jgame.secondarymarket.domain.product.repository.db;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jgame.secondarymarket.domain.product.entity.Product;
import com.jgame.secondarymarket.domain.product.repository.ProductRepository;
import com.jgame.secondarymarket.domain.product.repository.db.mapper.ProductMapper;
import com.jgame.secondarymarket.infrastructure.excetpions.BussnessException;
import com.jgame.secondarymarket.interfaces.query.page.product.PageProductQuery;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * @title: ProductRepositoryImpl
 * @Author Wangsj
 * @Date: 2021/7/21
 */
@Service
public class ProductRepositoryImpl extends ServiceImpl<ProductMapper, Product> implements ProductRepository {
    @Override
    public Optional<Product> findById(Long productId) {
        return Optional.ofNullable(this.getById(productId));

    }

    @Override
    public void delById(Long productId) {
        this.removeById(productId);
    }

    @Override
    public IPage<Product> getPageProduct(PageProductQuery query) {
        Page<Product> productPage = new Page<>(query.getCurrent(), query.getSize());
        LambdaQueryWrapper<Product> queryWrapper = new QueryWrapper<Product>().lambda();

        //一级分类参数必须有
        queryWrapper.eq(Product::getCategoryFist, query.getCategoryFist());
        if (StrUtil.isNotBlank(query.getCategorySecond())) {
            queryWrapper.eq(Product::getCategorySecond, query.getCategorySecond());
        }
        if (StrUtil.isNotBlank(query.getName())) {
            queryWrapper.like(Product::getName, query.getName());
        }

        queryWrapper.orderByDesc(Product::getUpdateTime);
        return page(productPage, queryWrapper);
    }

    @Override
    public Product getProductOrThrow(Long productId) {
        return this.findById(productId)
                .orElseThrow(() -> BussnessException.throwException("该商品不存在"));
    }
}
